//
//  BDFillBusinessInfoStep2ViewController.m
//  HSY
//
//  Created by 陈浩 on 2017/4/12.
//  Copyright © 2017年 金开门. All rights reserved.
//

#import "BDFillBusinessInfoStep2ViewController.h"
#import "BDSaveShopInfoStep2Request.h"
#import "UIImagePickerController+Block.h"
#import "BQActivityView.h"
#import "BDUserShopModel.h"
#import "UIViewController+BDAddBusinessHelper.h"
#import "HCGDatePickerAppearance.h"
#import "NSString+Tools.h"
#import "BDSelectProvinceViewController.h"
#import "NSString+Validation.h"

@interface BDFillBusinessInfoStep2ViewController ()

@property (weak, nonatomic) IBOutlet UITextField *shopAbbreviationTextField;
@property (weak, nonatomic) IBOutlet UITextField *shopLocationTextField;
@property (weak, nonatomic) IBOutlet UITextField *shopDetailedAddressTextField;
@property (weak, nonatomic) IBOutlet UITextField *licenceStartDateTextFiled;
@property (weak, nonatomic) IBOutlet UITextField *licenceEndDateTextFIled;
@property (weak, nonatomic) IBOutlet UITextField *licenceNOTextFiled;

@property (weak, nonatomic) IBOutlet UIImageView *businessLicenseImageView;

@property (weak, nonatomic) IBOutlet UIButton *settlementTypeToPublicBtn;
@property (weak, nonatomic) IBOutlet UIButton *settlementTypeToPrivateBtn;
@property (weak, nonatomic) IBOutlet UIButton *takePhotoBtn;

@property (nonatomic, strong) BDSaveShopInfoStep2Request *task;

@end

@implementation BDFillBusinessInfoStep2ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.shopAbbreviationTextField.delegate = self;
    self.shopLocationTextField.delegate = self;
    self.shopDetailedAddressTextField.delegate =self;
    self.licenceNOTextFiled.delegate = self;
    self.licenceEndDateTextFIled.delegate = self;
    self.licenceStartDateTextFiled.delegate = self;
    
    [self.titleButton setTitle:@"店铺资料" forState:UIControlStateNormal];
    [self.rightAreaRBtn setTitle:@"下一步" forState:UIControlStateNormal];
    self.rightAreaRBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    [self.rightAreaRBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.rightArea.mas_right);
        make.width.mas_equalTo(@50);
        make.centerY.mas_equalTo(self.rightArea.mas_centerY);
        make.height.mas_equalTo(@30);
    }];

    
    [self.settlementTypeToPublicBtn setTitleColor:[UIColor colorWithHexString:@"6284dd"] forState:UIControlStateSelected];
    [self.settlementTypeToPrivateBtn setTitleColor:[UIColor colorWithHexString:@"6284dd"] forState:UIControlStateSelected];
    
    [self settlementTypeBtn:self.settlementTypeToPublicBtn backgroundColor:[UIColor whiteColor] borderColor:[UIColor colorWithHexString:@"bebebe"]];
    [self settlementTypeBtn:self.settlementTypeToPrivateBtn backgroundColor:[UIColor whiteColor] borderColor:[UIColor colorWithHexString:@"bebebe"]];
    
    
    self.task = [[BDSaveShopInfoStep2Request alloc] init];
    self.task.mainStoreID = [NSString stringWithFormat:@"%ld",(long)self.model.shopId];
    
    [self settlementTypeToPrivateBtnClick:nil];
    
    [self fillbackIfNeed];

}

- (void)fillbackIfNeed{
    if (!self.userShopModel) return;
    self.shopAbbreviationTextField.text = self.userShopModel.appBizShop.shortName; //店铺简称
    self.shopLocationTextField.text = self.userShopModel.appBizShop.districtName; //地址
    self.shopDetailedAddressTextField.text = self.userShopModel.appBizShop.address;
    self.licenceStartDateTextFiled.text = self.userShopModel.appBizShop.licenceStartDate;
    self.licenceEndDateTextFIled.text = self.userShopModel.appBizShop.licenceEndDate;
    self.licenceNOTextFiled.text = self.userShopModel.appBizShop.licenceNO;

    
    self.task.districtCode = self.userShopModel.appBizShop.districtCode;

    NSString *startDateString = self.userShopModel.appBizShop.licenceStartDate;
    NSString *endDateString = self.userShopModel.appBizShop.licenceEndDate;

    
    if (startDateString.length > 0) {
        self.task.licenceStartDate = startDateString;
        self.licenceStartDateTextFiled.text = [NSString dateString:startDateString fromFormatter:@"yyyy-MM-dd" toFormatter:@"yyyy年MM月dd日"];
    }
    
    if (endDateString.length > 0) {
        self.task.licenceEndDate = endDateString;
        self.licenceEndDateTextFIled.text = [NSString dateString:endDateString fromFormatter:@"yyyy-MM-dd" toFormatter:@"yyyy年MM月dd日"];
    }

    
    self.task.isPublic = self.userShopModel.appBizShop.isPublic;

    if (self.task.isPublic) {
        [self settlementTypeToPublicBtnClick:nil];
    }else{
        [self settlementTypeToPrivateBtnClick:nil];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)handleNavigationAction:(HSYNavigationActionType)actionType{
    if (actionType == HSYNavActionLeftAreaLeft) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    if (actionType == HSYNavActionRightAreaRight) {
        [self goNext:nil];
    }
}


-(void)settlementTypeBtn:(UIButton *)btn  backgroundColor:(UIColor *)bgcolor borderColor:(UIColor *) borderColor{
    btn.clipsToBounds = YES;
    btn.layer.borderColor = borderColor.CGColor;
    btn.backgroundColor = bgcolor;
    btn.layer.borderWidth = 0.5;
}

-(BOOL)checkDataIntegrity{
    self.task.shortName = self.shopAbbreviationTextField.text;
    self.task.address = self.shopDetailedAddressTextField.text;
    self.task.licenceNO = self.licenceNOTextFiled.text;
    self.model.shortName = self.shopAbbreviationTextField.text;

    if (!self.task.shortName.length) {
        [self showMessage:@"请填写商铺简称"];
        return NO;
    }else if([self.task.shortName isValidShopShortName]){
        [self showMessage:@"店铺名称限制为5-25个字数"];
        return NO;
    }
    
    if (!self.task.address.length) {
        [self showMessage:@"请填写详细地址"];
        return NO;
    }else if([self.task.address isValideAddress]){
        [self showMessage:@"街道名称限制为5-35个字数"];
        return NO;
    }
    
    if (!self.settlementTypeToPublicBtn.selected && !self.settlementTypeToPrivateBtn.selected) {
        [self showMessage:@"请选择结算类型"];
        return NO;
    }
    
    if (!self.task.districtCode.length) {
        [self showMessage:@"请选择商铺所在地"];
        return NO;
    }
    
    if (!self.task.imageFile && self.task.isPublic == 1) {
        [self showMessage:@"请选择营业执照"];
        return NO;
    }
    
    
    if ( self.task.isPublic == 1) {
        if (self.task.licenceNO.length == 0) {
            [self showMessage:@"对公营业执照号必填"];
            return NO;
        }else if (![self.task.licenceNO isValideLicenceNO]){
            [self showMessage:@"请输入正确营业执照号"];
            return NO;
        }
        
        if (self.task.licenceStartDate.length == 0) {
            [self showMessage:@"对公营业执照开始日期必填"];
            return NO;
        }
        
        if (self.task.licenceEndDate.length == 0) {
            [self showMessage:@"对公营业执照结束日期必填"];
            return NO;
        }
        
        if (!self.businessLicenseImageView.image) {
            [self showMessage:@"对公营业执照照片必填"];
            return NO;
        }
        
    }
    
    return YES;
}




- (IBAction)selectProvincesBtnClick:(id)sender {
    if (self.readOnly) return;
    
    [self.view endEditing:YES];
    //选择省市
    
    BDSelectProvinceViewController *vc = [[BDSelectProvinceViewController alloc] init];
    __weak typeof(self) weakSelf = self;
    
    [vc getProvinceCityCountyinfo:^(NSString *title, NSString *code) {
        weakSelf.shopLocationTextField.text = title;
        weakSelf.task.districtCode = code;
    }];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)commitData{
    [self.view endEditing:YES];
    
    if (![self checkDataIntegrity]) return;
    
    [BQActivityView showActiviTy];
    __weak typeof(self)weakSelf = self;
    
    [BDNetworkManager POST:self.task completionHander:^(id responseObject, NSString *resultString) {
        [BQActivityView hideActiviTy];
        
        if (responseObject) {
            BDBusinessModel *model = [BDBusinessModel mj_objectWithKeyValues:responseObject];
            weakSelf.model.status = model.status;
            weakSelf.model.auStep = model.auStep;
            //go to next step
            [weakSelf nextStepWihBusinessModel:weakSelf.model userShopModel:weakSelf.userShopModel readOnly:weakSelf.readOnly];
            
        }else{
            if (resultString) {
                [weakSelf showMessage:resultString];
            }
        }
    }];
}

- (IBAction)goNext:(id)sender {
    [self handleNext];
}


- (IBAction)chooseStartDateClcik:(id)sender {
    if (self.readOnly) return;
    __weak typeof(self)weakSelf = self;
    
    HCGDatePickerAppearance *picker = [[HCGDatePickerAppearance  alloc] initWithDatePickerMode:DatePickerDateMode completeBlock:^(NSDate *date) {
        weakSelf.task.licenceStartDate = [NSString dateStringFrom1970:[date timeIntervalSince1970] formatter:@"yyyy-MM-dd"];
        weakSelf.licenceStartDateTextFiled.text = [NSString dateStringFrom1970:[date timeIntervalSince1970] formatter:@"yyyy年MM月dd日"];
        
        [picker hide];

    }];
    
    [picker show];
}

- (IBAction)chooseEndDateClick:(id)sender {
    if (self.readOnly) return;
    __weak typeof(self)weakSelf = self;
    
    HCGDatePickerAppearance *picker = [[HCGDatePickerAppearance  alloc] initWithDatePickerMode:DatePickerDateMode completeBlock:^(NSDate *date) {
        
        weakSelf.task.licenceEndDate = [NSString dateStringFrom1970:[date timeIntervalSince1970] formatter:@"yyyy-MM-dd"];
        weakSelf.licenceEndDateTextFIled.text = [NSString dateStringFrom1970:[date timeIntervalSince1970] formatter:@"yyyy年MM月dd日"];
        
        [picker hide];
    }];
    
    [picker show];
    
}

- (IBAction)settlementTypeToPublicBtnClick:(UIButton *)sender {
    if (sender && self.readOnly) return;

    self.task.isPublic = 1;
    
    self.settlementTypeToPublicBtn.selected = YES;
    self.settlementTypeToPrivateBtn.selected = NO;
    
    self.model.isPublic = 1;
    
    [self settlementTypeBtn:self.settlementTypeToPublicBtn backgroundColor:[UIColor colorWithHexString:@"f2f6ff"] borderColor:[UIColor colorWithHexString:@"7a97e3"]];
    [self settlementTypeBtn:self.settlementTypeToPrivateBtn backgroundColor:[UIColor whiteColor] borderColor:[UIColor colorWithHexString:@"bebebe"]];
}

- (IBAction)settlementTypeToPrivateBtnClick:(UIButton *)sender {
    if (sender && self.readOnly) return;
    self.task.isPublic = 0;
    
    self.settlementTypeToPrivateBtn.selected = YES;
    self.settlementTypeToPublicBtn.selected = NO;
    
    self.model.isPublic = 0;
    
    [self settlementTypeBtn:self.settlementTypeToPrivateBtn backgroundColor:[UIColor colorWithHexString:@"f2f6ff"] borderColor:[UIColor colorWithHexString:@"7a97e3"]];
    [self settlementTypeBtn:self.settlementTypeToPublicBtn backgroundColor:[UIColor whiteColor] borderColor:[UIColor colorWithHexString:@"bebebe"]];
    
}
- (IBAction)takePhotoBtnClcik:(UIButton *)sender {
    if (self.readOnly) return;
    
    __weak typeof(self) wSelf = self;
    UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] initWithSourceType:UIImagePickerControllerSourceTypeCamera finish:^(UIImagePickerController *vc, UIImage *image) {
        wSelf.businessLicenseImageView.image = image ;
        [wSelf.takePhotoBtn setImage:nil forState:UIControlStateNormal];
        
        wSelf.task.imageFile = UIImageJPEGRepresentation(wSelf.businessLicenseImageView.image, 0.1);

    }];
    
    [self presentViewController:imagePickerVC animated:YES completion:nil];

}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    BOOL b = [super textFieldShouldBeginEditing:textField];
    
    if (b && (textField == self.shopLocationTextField || textField == self.licenceStartDateTextFiled || textField == self.licenceEndDateTextFIled)) {
        b = NO;
    }
    return b;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
